<script setup lang="ts">
import { ref, onMounted } from "vue";
import { fabric } from "fabric";

const canvas = ref(null);

onMounted(() => {
  var canvas = new fabric.Canvas("canvasfabric", { selection: false });
  fabric.Object.prototype.originX = fabric.Object.prototype.originY = "center"; //所有图形的绘制起点都是中间点

  const initEvent = () => {
    //   监听鼠标点击事件
    canvas.on("mouse:down", (options) => {
      console.log(
        `x轴坐标: ${options.e.clientX};    y轴坐标: ${options.e.clientY}`
      );
    });
  };

  function makeLine(coords) {
    return new fabric.Line(coords, {
      fill: "red",
      stroke: "red",
      strokeWidth: 5,
      selectable: false,
      evented: false,
    });
  }
  function makeCircle(name, left, top, line1?, line2?, line3?, line4?) {
    var c = new fabric.Circle({
      name: name,
      left: left,
      top: top,
      strokeWidth: 2,
      radius: 6,
      fill: "#ff0",
      stroke: "#000",
    });
    c.hasControls = c.hasBorders = false;

    c.line1 = line1;
    c.line2 = line2;
    c.line3 = line3;
    c.line4 = line4;

    return c;
  }

  initEvent();

  const line1 = makeLine([250, 125, 250, 175]);
  const line2 = makeLine([250, 175, 400, 175]);
  
  canvas.add(line1);
  canvas.add(line2);
  canvas.add(
    makeCircle("circle1", line1.get("x2"), line2.get("y2"), line1, line2)
  );
  canvas.add(
    makeCircle("circle2", line1.get("x1"), line1.get("y1"), null, line1)
  );
  canvas.add(makeCircle("circle3", line2.get("x2"), line2.get("y2"), line2));

  canvas.on("object:moving", function (e) {
    var p = e.target;
    p.line1 && p.line1.set({ x2: p.left, y2: p.top });
    p.line2 && p.line2.set({ x1: p.left, y1: p.top });
    p.line3 && p.line3.set({ x1: p.left, y1: p.top });
    p.line4 && p.line4.set({ x1: p.left, y1: p.top });
    canvas.renderAll();
  });

  canvas.on("object:modified", function (e) {
    console.log(`修改了:${e.target.name}`, e);
  });
});
</script>

<template>
    <p>使用fabric.line来实现</p>
  <canvas id="canvasfabric" width="800" height="800" ref="canvas"></canvas>
</template>

<style lang="scss"></style>
